package com.salesmanager.web.admin.controller.categories;

import com.salesmanager.core.business.category.model.Category;
import com.salesmanager.core.business.category.model.status.CategoryStatus;
import com.salesmanager.core.business.category.service.CategoryService;

import com.salesmanager.web.admin.controller.AbstractController;
import com.salesmanager.web.admin.controller.ControllerConstants;
import com.salesmanager.web.constants.Constants;
import com.salesmanager.web.entity.catalog.category.ReadableCategory;
import com.salesmanager.web.populator.catalog.ReadableCategoryPopulator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import java.util.*;

/**
 * Created by Liutong on 2016/6/6.
 */
@Controller
public class CategoryController extends AbstractController {

    @Autowired
    CategoryService categoryService;

    @RequestMapping(value = "categories/categories/lv2", method = RequestMethod.GET)
    public String displayCategoriesForLv2(@RequestParam(required = false) String status,@RequestParam Long parentId,Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        super.setMenu(model, request, Collections.singletonList("catalogue-categories"), "catalogue-categories");

        Category parentCategory = categoryService.getById(parentId);

        List<Category> categoryList = categoryService.listByParentId(parentId);
        ReadableCategoryPopulator categoryPopulator = new ReadableCategoryPopulator();
        categoryPopulator.setRequest(request);

        List<ReadableCategory> readableCategories = new ArrayList<ReadableCategory>();
        for (Category category : categoryList){
            if (status != null && !status.equals("-1")){
                if (category.getCategoryStatus().toString().equals(status)){
                    readableCategories.add(categoryPopulator.populate(category,new ReadableCategory()));
                }
            }else{
                readableCategories.add(categoryPopulator.populate(category,new ReadableCategory()));
            }
        }

        model.addAttribute("categoryList", readableCategories);
        model.addAttribute("categoryStatus", Arrays.asList(CategoryStatus.values()));
        model.addAttribute("status",status);
        model.addAttribute("parentName",parentCategory.getName());
        model.addAttribute("parentId",parentId);

        return ControllerConstants.Tiles.Category.categorysLv2;
    }


    @RequestMapping(value = "categories/editCategory", method = RequestMethod.GET)
    public String displayCategoryEdit(@RequestParam("id") long categoryId,@RequestParam int lv, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        return displayCategory(categoryId, lv,model, request, response);

    }

    @RequestMapping(value = "categories/save", method = RequestMethod.POST)
    public String saveCategory(@Valid @ModelAttribute("category") Category category,@RequestParam int lv, BindingResult result, Model model, HttpServletRequest request) throws Exception {
        //display menu
        super.setMenu(model, request, Collections.singletonList("catalogue-categories"),"catalogue-categories");

        //验证code
        Category currentCategory = categoryService.getByCode(category.getCode());
        if (currentCategory != null){
            if (!currentCategory.getId().equals(category.getId())){
                result.rejectValue("code","code","编码已存在");
            }
        }

        if (result.hasErrors()) {
            return ControllerConstants.Tiles.Category.categoryEdit;
        }

        Category newCategory = category;

        if (category.getId() != null && category.getId() > 0){
            //copy attr
            newCategory = categoryService.getById(category.getId());
            newCategory.setParent(category.getParent());
            newCategory.setCategoryStatus(category.getCategoryStatus());
            newCategory.setSortOrder(category.getSortOrder());

            newCategory.setTitle(category.getTitle());
            newCategory.setName(category.getName());
            newCategory.setMetatagKeywords(category.getMetatagKeywords());
            newCategory.setDescription(category.getDescription());
        }
        newCategory.setVisible(true);
        //check parent
        if (category.getParent() == null) {
            //this is a root category
            newCategory.setParent(null);
            newCategory.setLineage("/");
            newCategory.setDepth(0);
        }

        newCategory.getAuditSection().setModifiedBy(request.getRemoteUser());

        categoryService.saveOrUpdate(newCategory);

        //ajust lineage and depth
        if (newCategory.getParent() != null && newCategory.getParent().getId() != -1) {
            Category parent = new Category();
            parent.setId(newCategory.getParent().getId());

            categoryService.addChild(parent, newCategory);
        }

//        category.setCategory(newCategory);

        //get parent categories
        List<Category> allCategories = categoryService.listByDepth(lv - 2);
        model.addAttribute("categories", allCategories);
        model.addAttribute("categoryStatus", Arrays.asList(CategoryStatus.values()));
        model.addAttribute("lv",lv);
        model.addAttribute("category",category);

        model.addAttribute("success", "success");
        return ControllerConstants.Tiles.Category.categoryEdit;
    }



    //category list 一级分类
    @RequestMapping(value = "categories/categories", method = RequestMethod.GET)
    public String displayCategories(@RequestParam(required = false) String status,Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        super.setMenu(model, request, Collections.singletonList("catalogue-categories"), "catalogue-categories");

        List<Category> categoryList = categoryService.listByDepth(0);
        ReadableCategoryPopulator categoryPopulator = new ReadableCategoryPopulator();
        categoryPopulator.setRequest(request);

        List<ReadableCategory> readableCategories = new ArrayList<ReadableCategory>();
        for (Category category : categoryList){
            if (status != null && !status.equals("-1")){
                if (category.getCategoryStatus() != null && category.getCategoryStatus().toString().equals(status)){
                    readableCategories.add(categoryPopulator.populate(category,new ReadableCategory()));
                }
            }else{
                readableCategories.add(categoryPopulator.populate(category,new ReadableCategory()));
            }
        }

        model.addAttribute("categoryList", readableCategories);
        model.addAttribute("categoryStatus", Arrays.asList(CategoryStatus.values()));
        model.addAttribute("status",status);

        return ControllerConstants.Tiles.Category.categorysLV1;
    }

    @RequestMapping(value = "categories/createCategory", method = RequestMethod.GET)
    public String displayCategoryCreate(@RequestParam int lv,Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        return displayCategory(null, lv, model, request, response);

    }


    private String displayCategory(Long categoryId,int lv, Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //display menu
        super.setMenu(model, request, Collections.singletonList("catalogue-categories"), "catalogue-categories");

        //get parent categories
//        CategorySeasonEntity categorySeasonEntity = new CategorySeasonEntity();
        List<Category> allCategories = categoryService.listByDepth(lv - 2);

        Category category = new Category();

        if (categoryId != null && categoryId != 0) {//edit mode
            category = categoryService.getById(categoryId);

            if (category == null) {
                return ControllerConstants.Tiles.Category.categorysLV1;
            }

//            if (lv>=2){
//
//                String[] priceGroup = null;
//                //get priceInterval
//                if (!org.apache.commons.lang.StringUtils.isBlank(category.getPriceInterval())){
//                    priceGroup = category.getPriceInterval().split(";");
//
//                    String[] group0 = priceGroup[0].split(",");
//                    categorySeasonEntity.setLowPriceFirst(group0[0]);
//                    categorySeasonEntity.setHighPriceFirst(group0[1]);
//
//                    String[] group1 = priceGroup[1].split(",");
//                    categorySeasonEntity.setLowPriceSecond(group1[0]);
//                    categorySeasonEntity.setHighPriceSecond(group1[1]);
//
//                    String[] group2 = priceGroup[2].split(",");
//                    categorySeasonEntity.setLowPriceThird(group2[0]);
//                    categorySeasonEntity.setHighPriceThird(group2[1]);
//
//                }
//            }

        }

        category.setVisible(true);


//        CategoryDescription description = category.getDescription();
//
//        if (description == null) {
//            description = new CategoryDescription();
//        }
//
//        category.setDescription(description);

//        if (lv>=2){
//            List<SeasonEntity> seasonEntities = getSeasonEntity(categoryId);
//            model.addAttribute("seasonEntities", seasonEntities);
//
//        }
//        categorySeasonEntity.setCategory(category);
        model.addAttribute("category", category);
        model.addAttribute("categories", allCategories);
        model.addAttribute("categoryStatus", Arrays.asList(CategoryStatus.values()));
        model.addAttribute("lv",lv);

        return ControllerConstants.Tiles.Category.categoryEdit;
    }

}
